package battle

import (
	"server/game/model"

	"github.com/hwcer/updater"
	"github.com/hwcer/yyds/context"
	"github.com/hwcer/yyds/players/player"
)

const MiddlewareName = "BattleMiddlewareName"

const (
	MiddlewareTypeFWBoss int8 = iota + 1
	MiddlewareTypeMainStory
	MiddlewareTypeNewStage
	MiddlewareTypeChallenge
	MiddlewareTypeActStage
)

var db = model.DB()

func Register(i interface{}, name ...string) {
	arr := []string{"battle"}
	if len(name) > 0 {
		arr = append(arr, name...)
	} else {
		arr = append(arr, "%v")
	}

	context.Register(i, arr...)
}

type Middleware struct {
	T int8
	K int32
	V any
	//S string //UID PVP
}

func (mw *Middleware) Emit(u *updater.Updater, eventType updater.EventType) bool {
	return mw.T > 0
}

func (mw *Middleware) Is(t int8) bool {
	return mw.T == t
}

//func (mw *Middleware) Delete() {
//	mw.T = 0
//	mw.K = 0
//	mw.V = nil
//}

func (mw *Middleware) Release(*updater.Updater) bool {
	return true
}

//func createMiddleware() updater.Middleware {
//	return &Middleware{}
//}

func (mw *Middleware) Create(p *player.Player, t int8, id int32, v any) {
	i := p.Events.LoadOrStore(MiddlewareName, mw)
	m := i.(*Middleware)
	m.T = t
	m.K = id
	m.V = v
	*mw = *m
}

func (mw *Middleware) Verify(p *player.Player, t int8, id int32) bool {
	i := p.Events.Get(MiddlewareName)
	if i == nil {
		return false
	}
	sm := i.(*Middleware)
	if sm.T != t {
		return false
	}
	if id != 0 && sm.K != id {
		return false
	}
	*mw = *sm
	sm.T = 0
	sm.K = 0
	sm.V = nil
	return true
}
